package top.leyi.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.leyi.IService.IActivityService;
import top.leyi.entity.user.SimpleUser;
import top.leyi.entity.user.User;
import top.leyi.entity.activity.Activity;
import top.leyi.entity.SQLUtil;
import top.leyi.entity.activity.DetailActivity;
import top.leyi.entity.activity.SimpleActivity;
import top.leyi.mapper.ActivityMapper;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    @Qualifier("activityMapper")
    ActivityMapper mapper;

    @Override
    public List<SimpleActivity> getSimpleActivity(int page) {
        SQLUtil util = new SQLUtil();
        util.setLimit(LIMIT);
        util.setOffset((page - 1) * LIMIT);


        return mapper.querySimpleActivity(util);
    }

    @Override
    public List<DetailActivity> getDetActivity(int page) {
        SQLUtil util = new SQLUtil();
        util.setLimit(LIMIT);
        util.setOffset((page - 1) * LIMIT);


        return mapper.queryDetilActivity(util);
    }

    @Override
    public DetailActivity getActivity(int id, User user) {

        DetailActivity detailActivity =  mapper.queryActivity(id);
        int userId = user.getId();
        List<SimpleUser> users = mapper.queryJoinPeople(id);

        detailActivity.setJoinPeople( users);

        users.forEach((e)->{
            if(e.getId() == userId){
                detailActivity.setHasJoin(true);
                return;
            }
        });

        return detailActivity;
    }

    @Override
    public void addActivity(Activity activity, User user){
          mapper.addActivity(activity);
    };



    public void updateActivity(Activity activity, User user){
         mapper.updateActivity(activity);
    };

    public void deleteActivity(Activity activity, User user){
         mapper.deleteActivity(activity);
    };


    @Transactional
    public DetailActivity joinOrCancelOneActivity(int id, User user) {

          int userId = user.getId();
          DetailActivity activity = new DetailActivity();
          activity.setId(id);
          activity.setUserId(userId);
          boolean hasJoin = queryHasJoin(activity);

         if(hasJoin)
             mapper.cancelActivity(activity);
         else
            mapper.joinActivity(activity);

         return getActivity(id, user);
    }


    @Transactional
    boolean queryHasJoin( DetailActivity activity){
        return mapper.queryIsJoin(activity) > 0;
    }
}
